package com.tongji.run.manager;

import com.ibeetl.admin.core.util.PlatformException;
import com.spire.xls.*;
import com.tongji.utils.JxlsUtils;
import org.beetl.sql.core.*;
import org.beetl.sql.core.db.DBStyle;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.ext.DebugInterceptor;

import javax.print.PrintService;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
public class ManagerFactory {
    public static SQLManager taibangSqlManager() {
        ConnectionSource source = ConnectionSourceHelper.getSimple("com.mysql.cj.jdbc.Driver", "jdbc:mysql://10.1.17.253:3306/plasma?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false&useInformationSchema=true", "plasma", "szrouting2004plasma");
        DBStyle mysql = new MySqlStyle();
        // sql语句放在classpagth的/sql 目录下
        SQLLoader loader = new ClasspathLoader("/sql");
        // 数据库命名跟java命名一样，所以采用DefaultNameConversion，还有一个是UnderlinedNameConversion，下划线风格的，
        UnderlinedNameConversion nc = new  UnderlinedNameConversion();
        // 最后，创建一个SQLManager,DebugInterceptor 不是必须的，但可以通过它查看sql执行情况
        SQLManager sqlManager = new SQLManager(mysql,loader,source,nc,new Interceptor[]{new DebugInterceptor()});

        return sqlManager;
    }

    public static SQLManager jiangzhanSqlManager() {
        ConnectionSource source = ConnectionSourceHelper.getSimple("com.mysql.cj.jdbc.Driver", "jdbc:mysql://127.0.0.1:3306/tongji?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false&useInformationSchema=true", "root", "");
        DBStyle mysql = new MySqlStyle();
        // sql语句放在classpagth的/sql 目录下
        SQLLoader loader = new ClasspathLoader("/sql");
        // 数据库命名跟java命名一样，所以采用DefaultNameConversion，还有一个是UnderlinedNameConversion，下划线风格的，
        UnderlinedNameConversion nc = new  UnderlinedNameConversion();
        // 最后，创建一个SQLManager,DebugInterceptor 不是必须的，但可以通过它查看sql执行情况
        SQLManager sqlManager = new SQLManager(mysql,loader,source,nc,new Interceptor[]{new DebugInterceptor()});

        return sqlManager;
    }

    public static File createExcel(String root, String excelTemplate, String filePath, Map data) {
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            File f = new File(root + filePath);
            f.getParentFile().mkdirs();
            FileOutputStream os = new FileOutputStream(f);
            JxlsUtils.exportExcel(is,os,data);
            return f;
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }
    }

    public static void createAndPrintExcel(String root, String excelTemplate, String filePath, Map data) {
    }

    public static void main(String[] args) {
        //创建一个Workbook类的对象
        Workbook workbook = new Workbook();
        //载入Excel文件
        workbook.loadFromFile("E:\\文档\\2023\\回访记录\\检疫期回访记录\\2022年12月16日至2022年12月16日\\0自来-检疫期回访名单（3）.xls");
        //获取第一个工作表
        Worksheet worksheet = workbook.getWorksheets().get(0);
        //从第一个工作表获取PageSetup类的对象
        PageSetup pageSetup = worksheet.getPageSetup();

        //设置页边距
        pageSetup.setTopMargin(0.3);
        pageSetup.setBottomMargin(0.3);
        pageSetup.setLeftMargin(0.3);
        pageSetup.setRightMargin(0.3);

        //指定要打印的区域
        pageSetup.setPrintArea("A1:C18");

        //指定标题行
        pageSetup.setPrintTitleRows("$1:$1");

        //允许打印标题
        pageSetup.isPrintHeadings(true);

        //允许打印网格线
        pageSetup.isPrintGridlines(true);

        //允许打印并显示批注
        pageSetup.setPrintComments(PrintCommentType.InPlace);

        //设置打印质量(dpi)
        pageSetup.setPrintQuality(300);

        //允许黑白模式打印
        pageSetup.setBlackAndWhite(true);

        //设置打印顺序
        pageSetup.setOrder(OrderType.OverThenDown);

        //将工作表排布在一页上
        pageSetup.isFitToPage(true);

        //创建一个Paper类的对象
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        PageFormat pageFormat = printerJob.defaultPage();
        Paper paper = pageFormat.getPaper();

        //设置纸张的可绘制区域
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

        //设置打印份数
        printerJob.setCopies(1);
        pageFormat.setPaper(paper);

        //以设定的格式渲染工作簿
        printerJob.setPrintable(workbook, pageFormat);

        //执行打印
        try {
            printerJob.print();
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }


    public static PrinterJob getPrintServiceByName(String printerName) {
        PrinterJob job = PrinterJob.getPrinterJob();
        // 遍历查询打印机名称
        boolean flag = false;
        for (PrintService ps : PrinterJob.lookupPrintServices()) {
            String psName = ps.toString();
            // 选用指定打印机，需要精确查询打印机就用equals，模糊查询用contains
            if (psName.contains(printerName)) {
                flag = true;
                try {
                    job.setPrintService(ps);
                } catch (PrinterException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
        if(!flag){
            throw new RuntimeException("打印失败，未找到名称为" + printerName + "的打印机，请检查。");
        }
        return job;
    }
}
